// qiniu 上传图片、视频方法
import dayjs from 'dayjs';
import { COS_CONF } from '../constants/common';
import { isObject, randomString } from './utils';
import { getQiniuToken } from '../biztools/wex';
import { chooseImage, getImageInfo, chooseVideo, getVideoInfo, uploadFile, showLoading, hideLoading, tipSuccess, tipError, canIUse } from './env';
import { getUploadToken } from '../api/common';

// 上传图片 type 业务类型
const uploadImage = async (type, file) => {
    if (!file) file = (await chooseImage())[0];
    const fileInfo = await getImageInfo(isObject(file) ? file.url : file);
    const key = `bgp-mini-image/${type}_${dayjs().format('YYYYMMDD')}_${randomString(12)}.${fileInfo.type === 'jpeg' ? 'jpg' : fileInfo.type}`;
    showLoading('上传中...');
    const uploadKey = await uploadFileInBucket({
        key,
        file
    })
    if (uploadKey) {
        hideLoading();
        tipSuccess('上传成功');
    }
    return {
        url: `${uploadKey}`
    }
};

// 上传视频 type 业务类型
const uploadVideo = async (type, file) => {
    if (!file) file = await chooseVideo();
    let fileInfo = { type: 'mp4' };
    if (canIUse('getVideoInfo')) {
        fileInfo = await getVideoInfo(isObject(file) ? file.url : file);
    }
    const key = `bgp-mini-video/${type}_${dayjs().format('YYYYMMDD')}_${randomString(12)}.${fileInfo.type}`;
    showLoading('上传中...');
    const uploadKey = await uploadFileInBucket({
        key,
        file,
        filetype: 'video'
    })
    if (uploadKey) {
        hideLoading();
        tipSuccess('上传成功');
    }
    return {
        url: `${uploadKey}`
    }
};

const uploadFileInBucket = async ({ file, key, filetype = 'image' }) => {
    const qiniu = await qiniuToken({
        key,
        bucket: COS_CONF.bucketPrefix,
    })
    return uploadFile({
        url: 'https://upload.qiniup.com',
        filePath: isObject(file) ? file.url : file,
        name: 'file',
        formData: {
            token: qiniu.token,
            filetype,
            key
        },
    }).then(res => {
        let result = JSON.parse(res.data);
        if (result.error) {
            tipError(result.error);
            return '';
        } else {
            return result.key;
        }
    }, err => {
        console.log(err)
        tipError(err.errMsg)
        return '';
    });
}

const qiniuToken = async (data) => {
    let token = getQiniuToken();
    if (!token) {
        token = await getUploadToken();
    }
    return { token };
};

module.exports = {
    uploadImage,
    uploadVideo,
};
